import csv
import io
import chardet
from flask import Blueprint, jsonify, request
from flask_jwt_extended import jwt_required
from libs.conn import *
from libs.utils import *

system_logs_bp = Blueprint('system_logs', __name__)

@system_logs_bp.route('/api/get_system_logs')
@jwt_required()
def get_system_logs():
    log_time = request.args.get('log_time')
    search = request.args.get('search')
    page_size = int(request.args.get('page_size'))
    page_current = int(request.args.get('page_current'))
    sql = "FROM system_logs WHERE 1=1"
    params = []
    if log_time != None and log_time != '':
        sql += " AND log_time LIKE ?"
        params.append('%' + log_time + '%')
    if search != None and search != '':
        sql += " AND log_content LIKE ?"
        params.append('%' + search + '%')
    offset = (page_current - 1) * page_size
    rows = fetchall("SELECT * " + sql + " ORDER BY log_time DESC LIMIT ?, ?", tuple(params + [offset, page_size]))
    total_count = fetchvalue("SELECT COUNT(*) " + sql, tuple(params))
    return { 'status': 'ok', 'data': rows, 'page_total': total_count }
